import { Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import React, { useEffect, useRef, useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { ActionType, ProColumns } from '@ant-design/pro-table/lib/Table';
import { SorterResult } from 'antd/es/table/interface';
import { IOrganizeTableItem } from '@/pages/data.d';
import { ConnectState, IResponse } from '@/models/connect';
import { connect, Dispatch } from 'umi';

const UploadModel = React.lazy(() => import('./components/UploadModel'));
const DetailModel = React.lazy(() => import('./components/DetailModel'));

interface DataListProps {
  dispatch: Dispatch;
  dataRoleList: Array<any>;
}

const DataList: React.FC<DataListProps> = (props) => {
  const [queryParams, setQueryParams] = useState<{}>({}); // 表格搜索关键词
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建弹框
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false); // 详情弹框

  const { dataRoleList, dispatch } = props;

  // 查看详情
  const seeDetail = (record: any) => {
    dispatch({
      type: 'dataRole/fetchRoleDetail',
      payload: { no: record.no },
      callback: (response: IResponse) => {
        const { header } = response;
        if (header.code === 200) {
          handleDetailModalVisible(true);
        }
      },
    });
  };

  useEffect(() => {
    // 获取角色列表（表格数据）
    if (dataRoleList.length === 0) {
      dispatch({
        type: 'dataRole/fetchRoleList',
      });
    }
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '唯一标识ID',
      dataIndex: 'no',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      // @ts-ignore
      filters: false,
      valueEnum: {
        2: {
          text: '树形',
        },
        1: {
          text: '普通',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <>
          <a
            onClick={() => {
              seeDetail(record);
            }}
          >
            查看
          </a>
        </>
      ),
    },
  ];

  // 获得表格滚动区域高度
  let tabelScroll = 300;
  const wrapperRef = useRef<any>();

  if (wrapperRef && wrapperRef.current) {
    tabelScroll = wrapperRef.current.scrollHeight - 280;
  }

  return (
    <div>
      <ProTable<IOrganizeTableItem>
        actionRef={actionRef}
        scroll={{ y: tabelScroll }}
        rowKey='name'
        options={{
          fullScreen: true,
          reload: false,
          setting: true,
          density: true,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<IOrganizeTableItem>;

          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <Button type='primary' onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        dataSource={dataRoleList.filter((value) => {
          const keys = Object.keys(queryParams);
          if (keys.length === 0) {
            return true;
          }
          for (const i in keys) {
            const key = keys[i];
            if (value[key].toString().indexOf(queryParams[key]) === -1) {
              return false;
            }
          }

          return true;
        })}
        onSubmit={(params) => {
          setQueryParams(params);
        }}
        columns={columns}
      />

      {/* 新建弹框 */}
      {createModalVisible ? (
        <React.Suspense fallback={null}>
          <UploadModel
            modalVisible={createModalVisible}
            onCancel={() => {
              handleModalVisible(false);
            }}
          />
        </React.Suspense>
      ) : (
        ''
      )}

      {/* 详情弹框 */}
      {detailModalVisible ? (
        <React.Suspense fallback={null}>
          <DetailModel
            modalVisible={detailModalVisible}
            onCancel={() => {
              handleDetailModalVisible(false);
            }}
          />
        </React.Suspense>
      ) : (
        ''
      )}
    </div>
  );
};
export default connect(({ dataRole }: ConnectState) => ({
  dataRoleList: dataRole.dataRoleList || [],
}))(DataList);
